<?php

declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\controller\Backend;
use think\Exception;
use \think\facade\Cache;
use \app\admin\model\Category as CategoryModel;
use \app\admin\model\Album as AlbumModel;
use \app\admin\model\DocCon as DocConModel;
use think\facade\Db;
use think\facade\View;


class DocCon extends Backend
{
    public function initialize() {
        parent::initialize();
//        $this->_mod = Db::name('menu');
        $this->_mod  = new \app\admin\model\DocCon();
    }

    public function searchArr(){
        $where[]=array('del_status','=',1);
        $status = request()->param('status')?(int)request()->param('status'):-1;
        if($status >= 0) $where[]=array('status','=',$status);
        $cid = request()->param('cid')?(int)request()->param('cid'):-1;
        $catearr = '';
        if($cid >= 0) {
            $idarr = getcateallid($cid);
            if(is_array($idarr)){
                foreach ($idarr as $key =>$value){
                    if($key == 0){
                        $catearr = $value['id'];
                    } else{
                        $catearr.=','.$value['id'];
                    }
                }
            } else{
                $catearr = $idarr;
            }
            $where[]=array('cid','in',$catearr);
        }

        $title =  request()->param('title');
        if($title) $where[]=array('title','like','%'.$title.'%');
        View::assign('searchArr', array(
            'title'=>$title,
            'status' =>$status,
            'cid' =>$cid
        ));
        return $where;
    }



    public function _before_index(){
        $cate_mod =new CategoryModel();
        $where = $this->searchArr();
        $this->_list($this->_mod, $where, 'id', 'desc');
        $res = $cate_mod->field('id,name')->select();
        $cate_list = array();
        foreach ($res as $val) {
            $cate_list[$val['id']] = $val['name'];
        }
        View::assign('cate_list', $cate_list);
        $catelist = $cate_mod->where(array('pid'=>0,'status'=>1))->select();
        foreach ($catelist as $k => $v) {
            $catelist[$k]['erji'] = $cate_mod->where(array('pid'=>$v['id'],'status'=>1))->select();
        }
        View::assign('catelist', $catelist);
    }


    public function _before_add(){
        $doc_mod = new DocConModel();
        $cate_mod =new CategoryModel();
        $album_mod =new AlbumModel();
        $catelist = $cate_mod->where(array('pid'=>0,'status'=>1))->select();
        foreach ($catelist as $k => $v) {
            $catelist[$k]['erji'] = $cate_mod->where(array('pid'=>$v['id'],'status'=>1))->select();
        }
        $data['catelist']= $catelist;
        // 取专辑列表
        $zjlist = $album_mod->where('status',1)->select();
        $data['zjlist']= $zjlist;
        View::assign($data);
    }
    public function _before_insert($data){
        if(!$data['cid']) return '请选择分类';
    }
    public function _handle_insert($data){
        $fileinfo = explode('.', $data['fileurl']);
        $data['filename'] = $fileinfo[0];
        return $data;
    }
    public function _before_update($data){
        if(!$data['cid']) return '请选择分类';
    }
    public function _handle_update($data){
        $fileinfo = explode('.', $data['fileurl']);
        $data['filename'] = $fileinfo[0];
        return $data;
    }



    public function _before_edit(){
        $doc_mod = new DocConModel();
        $cate_mod =new CategoryModel();
        $album_mod =new AlbumModel();
        $catelist = $cate_mod->where(array('pid'=>0,'status'=>1))->select();
        foreach ($catelist as $k => $v) {
            $catelist[$k]['erji'] = $cate_mod->where(array('pid'=>$v['id'],'status'=>1))->select();
        }
        $data['catelist']= $catelist;
        // 取专辑列表
        $zjlist = $album_mod->where('status',1)->select();
        $data['zjlist']= $zjlist;
        $id = request()->param('id');
        $info = $doc_mod->where(array('id'=>$id))->find();
        $data['info']= $info;
        $cateid=$info['cid'];
        $pid=$cate_mod->where(array('id'=>$cateid))->value('pid');
        if($pid){
            $cateid=$pid.'|'.$cateid;
        }else{
            $cateid=$pid;
        }
        $data['cateid']= $cateid;
        View::assign($data);
    }

    public function ajax_upload(){
        $file = request()->file('file');  //这里‘file’是你提交时的name
        $paths = 'doc';
        $info = [
            'ext'=>$file->extension(),
            'size' => $file->getSize(),    // 文件名：读书顶个鸟用.jpg
            'name' => $file->getFilename(),    // 文件MINE：image/jpeg
            'mime' => $file->getMime(),
            'oldname'=>$file->getOriginalName(),
            'hash'=>$file->hash()
        ];
        try{
            validate(['goodFile' => [     //goodFile是你自定义的键名，目的是为了对check里数组中的
                'fileSize' =>50*1024*1024,//goodFile字段值进行验证;允许文件大小
                'fileExt'  => array('doc','docx','xls','xlsx','pptx','ppt','wps','et','pdf','txt'),  //允许的文件后缀
            ]])->check(['goodFile'=>$file]);//也就是对上传的$file进行验证

            $saveName = \think\facade\Filesystem::disk('public')->putFile( $paths, $file,
                function () use ($file){
                    switch ('date') {
                        case 'date':
                            $fileName = date('YmdHis').rand(1,9999).rand(1,9999);
                            break;
                        // 此项即为：保留原始文件名+日期方式
                        case 'original':
                            $fileName = str_replace('.'.$file->getOriginalExtension(),'',$file->getOriginalName().date('YmdHis'));
                            break;
                        default:
                            $fileName = uniqid();
                            break;
                    }
                    return $fileName;
                });//保存文件名
            $f_name = explode('/',$saveName);
            $info['name'] = end($f_name);
            $info['convert_key'] = $paths;
            $arr = ['status' => 1, 'msg' => '成功', 'info' => $info];
            return json($arr);   				//返回标准json格式
        }catch (\Exception $e) {
            return fail( 0, '上传失败!' . $e->getMessage());
        }
    }



    public function delete() {
        $pk = $this->_mod->getPk();
        $ids = explode(',', trim(request()->param($pk), ','));
        foreach ($ids as $id){
//            $map['id']=array('in',$ids);
            $map['id'] = $id;
            $return_arr[] = $this->_mod->where($map)->save(['del_status'=>2]);
        }
        if(in_array(0,$return_arr)){
            return fail(0,'删除失败','','');
        }
        return success(1,'删除成功','','add');
    }
}